<template>
    <div>
        <el-upload
                class="upload-demo"
                action=""
                :show-file-list="false"
                :http-request="importExcel"
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传 xlsx/xls 文件</div>
        </el-upload>
    </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import Blob from './Blob'
// eslint-disable-next-line no-unused-vars
import Export2Excel from './Export2Excel'

export default {
  methods: {
    importExcel(res) {
      const that = this
      this.file = res.file
      const rABS = false // 是否将文件读取为二进制字符串
      const f = this.file
      const reader = new FileReader()
      // eslint-disable-next-line func-names,no-shadow
      FileReader.prototype.readAsBinaryString = function (f) {
        let binary = ''
        // eslint-disable-next-line no-shadow
        const rABS = false // 是否将文件读取为二进制字符串
        let wb // 读取完成的数据
        let outdata
        // eslint-disable-next-line no-shadow
        const reader = new FileReader()
        // eslint-disable-next-line func-names
        reader.onload = function () {
          const bytes = new Uint8Array(reader.result)
          const length = bytes.byteLength
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i])
          }
          // eslint-disable-next-line global-require
          const XLSX = require('xlsx')
          if (rABS) {
            // eslint-disable-next-line no-undef
            wb = XLSX.read(btoa(fixdata(binary)), { type: 'base64' }) // 手动转化
          } else {
            wb = XLSX.read(binary, { type: 'binary' })
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
          that.$emit('importRequest', outdata) // 将处理好的json表格数据传给父组件
        }
        reader.readAsArrayBuffer(f)
      }
      if (rABS) {
        reader.readAsArrayBuffer(f)
      } else {
        reader.readAsBinaryString(f)
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
  },
}
</script>

<style scoped>
    .upload-demo {
        margin: 30px;
    }
    .el-upload__tip {
        margin-top: 30px;
    }
</style>
